<?php

namespace app\shop\controller;

use think\Request;
use think\Exception;
use app\shop\model\Cart as CartModel;

class Cart extends \PurchaseController
{
    /**
     * 用户购物车信息
     *
     * @return \think\Response
     */
    public function user()
    {
        $cartModel = new CartModel();

        $userId = \request()->header('userId');

        try {
            $items = $cartModel->where([
                'user_id' => $userId,
            ])
                ->relation('goods,goods.specs,goods.specs.values')
                ->order('create_at', 'desc')
                ->select();

            $this->successTerminate($items);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 购物车商品总数
     */
    public function total()
    {
        $cartModel = new CartModel();

        $userId = \request()->header('userId');

        try {
            $total = $cartModel
                ->where('user_id', $userId)
                ->sum('quantity');

            $this->successTerminate([
                'total' => $total
            ]);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $cartModel = new CartModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $cartModel = new CartModel();

        $data = $request->post();

        $data['user_id'] = $request->header('userId');

        /* @var $validate \ShopValidate */
        $validate = \think\Loader::validate('Cart');
        if ( !$validate->scene('save')->check($data) ) {
            return $validate->getError();
        }

        try {
            // 判断用户购物车中是否已加入该商品
            // - 已加入 更新记录的quantity字段
            // - 未加入 新增记录
            // 均需要确保quantity不能超过库存

            $item = $cartModel->where([
                'user_id' => $data['user_id'],
                'goods_id' => $data['goods_id'],
            ])->find();

            if (empty($item)) {
                $result = $cartModel->data($data)->allowField(true)->save();
            } else {
                $result = $cartModel->where([
                    'user_id' => $data['user_id'],
                    'goods_id' => $data['goods_id'],
                ])->setInc('quantity', $data['quantity']);
            }

            if (! $result) {
                $this->serverErrorTerminate('添加购物车失败');
            }

            return $this->total();
//            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }


    /**
     * 改变数量
     *
     * @param $goodsId
     * @param $quantity
     */
    public function changeQuantity($goodsId, $quantity)
    {
        $cartModel = new CartModel();

        $userId = \request()->header('userId');

        try {
            $data = $cartModel->save([
                'quantity' => $quantity,
            ],[
                'user_id' => $userId,
                'goods_id' => $goodsId,
            ]);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $cartModel = new CartModel();

        try {
            $data = $cartModel->get($id);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $cartModel = new CartModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $cartModel = new CartModel();
        $data = $request->post();

        $pk = $cartModel->getPk();
        if ( isset($data[$pk]) ) unset($data[$pk]);

        try {
            $result = $cartModel->allowField(true)->save($data, [
                $pk => $id,
            ]);
            if (! $result) $this->serverErrorTerminate('更新资源失败');
            $this->successTerminate($cartModel);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($goodsId)
    {
        $cartModel = new CartModel();

        $userId = \request()->header('userId');

        try {
            $affectedRowCount = $cartModel->where([
                'user_id' => $userId,
                'goods_id' => $goodsId,
            ])->delete();

            $affectedRowCount || $this->serverErrorTerminate('删除资源失败');

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }


    /**
     * 清空购物车
     *
     * @return \think\Response
     */
    public function truncate()
    {
        $cartModel = new CartModel();

        $userId = \request()->header('userId');

        try {
            $affectedRowCount = $cartModel->where([
                'user_id' => $userId,
            ])->delete();

            $affectedRowCount || $this->serverErrorTerminate('删除资源失败');

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
}
